#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
终端错误监控脚本
监控应用运行时的终端输出和错误信息
"""

import subprocess
import psutil
import time
import sys
import requests
from datetime import datetime

def check_process_status():
    """检查应用进程状态"""
    print("🔍 检查应用进程状态...")
    
    # 查找Python进程
    python_processes = []
    for proc in psutil.process_iter(['pid', 'name', 'cmdline', 'status']):
        try:
            if proc.info['name'] == 'python.exe':
                cmdline = ' '.join(proc.info['cmdline']) if proc.info['cmdline'] else ''
                if 'main.py' in cmdline:
                    python_processes.append({
                        'pid': proc.info['pid'],
                        'status': proc.info['status'],
                        'cmdline': cmdline
                    })
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            continue
    
    if python_processes:
        for proc in python_processes:
            print(f"✅ 发现应用进程:")
            print(f"   PID: {proc['pid']}")
            print(f"   状态: {proc['status']}")
            print(f"   命令行: {proc['cmdline']}")
            
            # 检查进程是否响应
            try:
                process = psutil.Process(proc['pid'])
                cpu_percent = process.cpu_percent(interval=1)
                memory_info = process.memory_info()
                print(f"   CPU使用率: {cpu_percent:.2f}%")
                print(f"   内存使用: {memory_info.rss / 1024 / 1024:.2f} MB")
            except Exception as e:
                print(f"   ⚠️ 无法获取进程详细信息: {e}")
        return python_processes
    else:
        print("❌ 未发现运行中的应用进程")
        return []

def test_application_response():
    """测试应用响应"""
    print("\n🌐 测试应用响应...")
    
    errors = []
    
    try:
        # 测试根路径
        response = requests.get("http://localhost:8005", timeout=5)
        if response.status_code == 200:
            print("✅ 应用响应正常")
        else:
            error_msg = f"应用返回异常状态码: {response.status_code}"
            print(f"⚠️ {error_msg}")
            errors.append(error_msg)
    except requests.exceptions.ConnectionError:
        error_msg = "无法连接到应用 - 可能已停止或端口被占用"
        print(f"❌ {error_msg}")
        errors.append(error_msg)
    except requests.exceptions.Timeout:
        error_msg = "应用响应超时"
        print(f"⚠️ {error_msg}")
        errors.append(error_msg)
    except Exception as e:
        error_msg = f"请求异常: {str(e)}"
        print(f"❌ {error_msg}")
        errors.append(error_msg)
    
    return errors

def check_port_conflicts():
    """检查端口冲突"""
    print("\n🔌 检查端口占用情况...")
    
    try:
        # 检查8005端口
        connections = psutil.net_connections(kind='inet')
        port_8005_found = False
        
        for conn in connections:
            # 检查本地地址和端口
            if conn.laddr and len(conn.laddr) >= 2:
                ip, port = conn.laddr[0], conn.laddr[1]
                if port == 8005 and ip in ['127.0.0.1', '0.0.0.0', '::', '::1']:
                    port_8005_found = True
                    try:
                        if conn.pid:
                            process = psutil.Process(conn.pid)
                            print(f"✅ 端口8005被进程占用:")
                            print(f"   PID: {conn.pid}")
                            print(f"   进程名: {process.name()}")
                            print(f"   状态: {conn.status}")
                            print(f"   地址: {ip}:{port}")
                        else:
                            print(f"✅ 端口8005被占用 (无PID信息)")
                            print(f"   状态: {conn.status}")
                            print(f"   地址: {ip}:{port}")
                    except Exception as e:
                        print(f"✅ 端口8005被占用 (无法获取进程信息: {e})")
                    break
        
        if not port_8005_found:
            print("❌ 端口8005未被占用 - 应用可能未启动")
    except Exception as e:
        print(f"⚠️ 检查端口时出错: {e}")

def monitor_system_errors():
    """监控系统错误"""
    print("\n🔬 检查系统错误...")
    
    # 检查Python警告
    import warnings
    warnings.simplefilter('always')
    
    try:
        # 测试导入主要模块
        import main
        print("✅ main.py 模块导入正常")
    except Exception as e:
        print(f"❌ main.py 导入错误: {e}")
        return [str(e)]
    
    try:
        # 测试其他关键模块
        import auth, rag_chain, text_processor, utils
        print("✅ 其他核心模块导入正常")
    except Exception as e:
        print(f"❌ 模块导入错误: {e}")
        return [str(e)]
    
    return []

def check_recent_errors():
    """检查最近的错误"""
    print("\n📋 检查最近的错误记录...")
    
    # 检查是否有最近生成的错误文件
    error_files = ['error.log', 'error_report.json', 'app.log']
    
    for error_file in error_files:
        try:
            with open(error_file, 'r', encoding='utf-8') as f:
                print(f"📄 发现错误文件: {error_file}")
                # 读取文件的最后几行
                content = f.read()
                if content.strip():
                    print(f"   文件大小: {len(content)} 字符")
                    if error_file == 'error_report.json':
                        import json
                        try:
                            data = json.loads(content)
                            print(f"   错误数量: {data.get('total_errors', 0)}")
                        except:
                            print("   JSON格式错误")
                else:
                    print("   文件为空")
        except FileNotFoundError:
            print(f"ℹ️ 未找到错误文件: {error_file}")
        except Exception as e:
            print(f"⚠️ 读取{error_file}时出错: {e}")

def main():
    """主监控函数"""
    print("🚀 开始终端错误监控")
    print("=" * 50)
    print(f"监控时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    
    # 1. 检查进程状态
    processes = check_process_status()
    
    # 2. 测试应用响应
    response_errors = test_application_response()
    
    # 3. 检查端口占用
    check_port_conflicts()
    
    # 4. 监控系统错误
    system_errors = monitor_system_errors()
    
    # 5. 检查最近错误
    check_recent_errors()
    
    # 6. 生成总结
    print("\n" + "=" * 50)
    print("📊 监控总结")
    print("-" * 30)
    
    total_errors = len(response_errors) + len(system_errors)
    
    if total_errors == 0:
        print("✅ 未发现终端错误")
        print("✅ 应用运行状态正常")
    else:
        print(f"⚠️ 发现 {total_errors} 个问题:")
        for error in response_errors + system_errors:
            print(f"   - {error}")
    
    if processes:
        print(f"✅ 发现 {len(processes)} 个应用进程在运行")
    else:
        print("❌ 未发现运行中的应用进程")
    
    print(f"\n🕐 监控完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

if __name__ == "__main__":
    main()